package com.bj58.mis.apm.server.statistics.service.impl;

import com.bj58.mis.apm.server.core.util.ParameterUtils;
import com.bj58.mis.apm.server.statistics.dto.common.Pair;
import com.bj58.mis.apm.server.statistics.dto.common.User;
import com.bj58.mis.apm.server.statistics.mapper.CommonMapper;
import com.bj58.mis.apm.server.statistics.service.BaseService;
import com.bj58.mis.apm.server.statistics.service.CommonService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wangxw
 * @Date: 2018/7/9 15:22
 */
@Service
@Transactional
public class CommonServiceImpl extends BaseService<CommonMapper> implements CommonService {
    @Override
    public List<Pair> queryProjects(String owner, String userName) {

        if(!super.isAdmin(userName)){
            return super.getAuthProjectIdList(userName);
        }

        List<String> cubeids = null;
        if(StringUtils.isEmpty(owner)){
            return this.mapper.queryProjects(null);
        }else{
            cubeids = this.getAuthCubeIdList(owner);
            if(cubeids == null || cubeids.isEmpty()){
                return new ArrayList<>();
            }else {
                return this.mapper.queryProjects(cubeids);
            }
        }
    }

    @Override
    public List<Pair> queryCubes(String projectId, String owner, String userName) {
        List<String> cubeids = null;

        if(!super.isAdmin(userName)){
            cubeids = this.getAuthCubeIdList(userName, projectId);
        }else{
            if(StringUtils.isEmpty(owner)){
                return this.mapper.queryCubes(projectId, null);
            }else {
                cubeids = this.getAuthCubeIdList(owner, projectId);
            }
        }

        if(cubeids == null || cubeids.isEmpty()){
            return new ArrayList<>();
        }else {
            return this.mapper.queryCubes(projectId, cubeids);
        }

    }

    @Override
    public List<Pair> qeuryOwners(String projectId, String keyword, String userName) {
        if(super.isAdmin(userName)){
            return super.getOwnersByRoc(projectId, ParameterUtils.getRLikeValue(keyword));
        }
        return new ArrayList<>();
    }

    @Override
    public User getCurrentUser(String userName){
        User user = new User();
        user.setUserName(userName);
        user.setAdmin(super.isAdmin(userName));
        return user;
    }

}
